//
//  GNComposeViewController.swift
//  SinaWeChat
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SnapKit

class GNComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    
    private func setupUI(){
        
        setupNav()
        view.backgroundColor = UIColor.whiteColor()
        
        //添加子控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(composePictureView)
        
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
            
        }
        
        //添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.width.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(44)
            
        }
        
        //因为能滚动,添加到textView上
        //宽度与高度一样
        //中心x与textView一样
        composePictureView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
            make.top.equalTo(textView).offset(100)
            
        }
        
        
        toolBar.childButtonClickClosure = {
            [weak self]
            (type: GNComposeToolBarButtonType) -> () in
            
            switch type{
                
            case .Picture:
                self?.selectImage()
                
            case .Mention:
                print ("@")
            case .Trend:
                print("#")
            case .Emotion:
                print("表情")
            case .Add :
                print("添加")
                
            }
        }
        
        //监听键盘弹出通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    
    
    //设置导航栏内容
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "返回", target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.enabled = false
        //设置中间
        navigationItem.titleView = titleView
        
    }
    
    
    @objc private func back(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //键盘frame高度改变的通知
    
    @objc private func keyboardWillChangeFrame(noti:NSNotification) {
        
        //取到键盘的结束位置
        
        let endRect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //取到动画执行时间
        let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        
        //把toolBar 的底部改成endRect的y
        toolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(self.view).offset(endRect.origin.y - self.view.height)
            
            }
        
        UIView.animateWithDuration(duration.doubleValue) { () -> Void in
            
            self.toolBar.layoutIfNeeded()
        }
        
    }
    
    //MARK: - 懒加载控件
    
    //发送按钮
    private lazy var sendButton:UIButton = {
        
        let button = UIButton()
       //设置不同状态的背景图
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        // 如果把 button 放在 UIBarButtonItem 里面,其状态由 UIBarButtonItem 控制
        
        //设置不同状态的文字颜色
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        
        //设置文字颜色及其大小
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        //指定其大小
        button.size = CGSize(width: 45, height: 30)
        return button
        
    }()
    
    //中间的titleView
    private lazy var titleView:UILabel = {
        
        let titleView = UILabel()
        
        if let name = GNUserAccountViewModel.sharedAccount.userAccount?.screen_name{
            
            //设置多行显示
            titleView.numberOfLines = 0
            
            //通过内容生成一个富文本对象
            let attrText = NSMutableAttributedString(string: "发微博\n\(name)")
            let range = (attrText.string as NSString).rangeOfString(name)
            
            //设置对应位置的字体属性
            let attrs = [NSFontAttributeName: UIFont.systemFontOfSize(14),NSForegroundColorAttributeName:UIColor.grayColor()]
            attrText.addAttributes(attrs, range: range)
            
            //设置成label上去
            titleView.attributedText = attrText
        }else{
            titleView.text = "发微博"
        }
        
        //文字居中
        titleView.textAlignment = .Center
        titleView.sizeToFit()
        return titleView
        
    }()
    
    //文字输入框
    private lazy var textView : GNComposeTextView = {
       
        let textView = GNComposeTextView()
        textView.font = UIFont.systemFontOfSize(16)
        textView.placeholder = "准备好,我要装逼了!!"
        
        //设置代理监听文字改变
        textView.delegate = self
        return textView
        
    }()
    
    //toolBar
    private lazy var toolBar:GNComposeToolBar = GNComposeToolBar(frame: CGRectZero)
    
    //初始化配图控件
    private lazy var composePictureView: GNComposePictureView = {
        
        let composePictureView = GNComposePictureView()
        
        //添加图片要调用的闭包
        composePictureView.addImageClosure = {
            [weak self] in
            
            //选择图片
            
        }
        
        composePictureView.backgroundColor = self.view.backgroundColor
        return composePictureView
    }()
    
}

// MARK: - 处理toolBar 按钮点击
extension GNComposeViewController{
    
    //选择图片
    private func selectImage(){
        //弹出选择照片的控制器
        let pictureVc = UIImagePickerController()
        
        //判断照相机能否用
        //let result = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        
        //判断照相机前后摄像头能否使用
        //UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front)
        //是否允许编辑图片
        //pictureVc.allowsEditing = true
        
        pictureVc.delegate = self
        presentViewController(pictureVc, animated: true, completion: nil)
        
    }
    
}



//MARK: -选择图片控制器的代理方法
extension GNComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        composePictureView.addImage(image)
        //关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        //点击取消
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}


//MARK: - UITextViewDelegate

extension GNComposeViewController : UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled  = textView.hasText()
    }
    
}